import { SharedMethodService } from './../../../@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { UserService } from './../../../@core/services/user/user.service';
import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { AddDepartmentComponent } from './department/add-department/add-department.component';
import { EditDepartmentComponent } from './department/edit-department/edit-department.component';
import { ResetPasswordComponent } from './employs/reset-password/reset-password.component';
@Component({
  selector: 'app-employs',
  templateUrl: './employs.component.html',
  styleUrls: ['./employs.component.scss']
})
export class EmploysComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  SearchTerm: string = null;
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData: any;
  allCheckedStatus = false;
  checkedIds = [];
  deleteIDs = [];
  editemployeeId: ""
  msgs: Array<Object> = [];
  option: any;//部门option
  departmentId: any;//部门id
  pathPids = []//部门树结构路径
  employData: any[] = [];//员工数据
  enabled: boolean = true;
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  searchDepartmentValue: any = ''
  filteredTreeNodes: any
  displayTreeData: any[];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '职员编码',
        fieldType: 'text',
        fixedLeft: '200px'
      },
      {
        field: 'name',
        header: '职员名称',
        fieldType: 'text',
        fixedLeft: '300px'
      },
      {
        field: 'workCode',
        header: '工号',
        fieldType: 'text'
      },
      {
        field: 'account',
        header: '账号',
        fieldType: 'text'
      },
      {
        field: 'departmentName',
        header: '部门',
        fieldType: 'text'
      },
      {
        field: 'isLeader',
        header: '部门领导',
        fieldType: 'boolean'
      },
      {
        field: 'station',
        header: '岗位',
        fieldType: 'text'
      },
      {
        field: 'gender',
        header: '性别',
        fieldType: 'text'
      },
      {
        field: 'mobile',
        header: '手机号',
        fieldType: 'text'
      },
      {
        field: 'bankName',
        header: '银行名称',
        fieldType: 'text'
      },
      {
        field: 'bankHolder',
        header: '开户人',
        fieldType: 'text'
      },
      {
        field: 'bankAccount',
        header: '银行账号',
        fieldType: 'text'
      },

      {
        field: 'contractStartDate',
        header: '入职日期',
        fieldType: 'text'
      },
      {
        field: 'idNumber',
        header: '身份证号',
        fieldType: 'text'
      },
      {
        field: 'email',
        header: '邮箱',
        fieldType: 'text'
      },
      {
        field: 'homeAddress',
        header: '家庭住址',
        fieldType: 'text'
      },
      {
        field: 'insuranceState',
        header: '参保情况',
        fieldType: 'text'
      },
      {
        field: 'isStay',
        header: '员工类型',
        fieldType: 'boolean'
      },
      {
        field: 'salaryType',
        header: '工资类别',
        fieldType: 'text'
      },
      {
        field: 'contractStartDate',
        header: '合同开始日期',
        fieldType: 'text'
      },
      {
        field: 'contractEndDate',
        header: '合同结束日期',
        fieldType: 'text'
      },
      {
        field: 'terminationDate',
        header: '离职日期',
        fieldType: 'text'
      },
      {
        field: 'enabled',
        header: '状态',
        fieldType: 'boolean',
        fixedRight: '0px'
      },
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '40px'
    },
    {
      field: 'name',
      width: '160px'
    },
    {
      field: 'value',
      width: '100px'
    },
    {
      field: 'description',
      width: '90px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    },
    {
      field: 'description',
      width: '100px'
    }
  ];//表格宽度配置
  selectoptions = [
    '全部', '启用', '禁用'
  ]
  selectvalue = '全部'
  tabledata = []
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }
  ) datatable!: DataTableComponent;//获取table
  displayTableData: any[];
  Status!: string;
  file: any;
  constructor(private dialogService: DialogService, private UserService: UserService, private Router: Router, private SharedMethodService: SharedMethodService) { }
  ngOnInit(): void {
    this.Status = this.selectvalue == '全部' ? "all" : this.selectvalue == '启用' ? "enable" : "disable"
    this.UserService.GetAllDepartments(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.treeData = data.items
      this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
      if (this.treeData.length > 0) {
        this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
          this.tabledata = data.items;
          this.displayTableData = this.tabledata;
          this.pager.total = data.totalCount;
          let departmentIdToName = {};
          this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
            departmentIdToName[item.departmentId] = item.name;
          });
          this.tabledata.forEach(item => {
            if (item.departmentId in departmentIdToName) {
              item.departmentId = departmentIdToName[item.departmentId];
            }
          });
        })
      }
    })
  }
  afterTreeInit($event: any) {
    if ($event["1"]) {
      $event["1"].data.isActive = true
    }
  }//树形菜单初始化
  getPathPids(node: any, nodes: any[]): string[] {
    let pathPids = [];
    let currentNode = node;
    while (currentNode && currentNode.parentDepartmentId) {
      pathPids.push(currentNode.parentDepartmentId);
      currentNode = nodes.find(n => n.departmentId === currentNode.parentDepartmentId);
    }
    pathPids = pathPids.reverse();
    pathPids.push(node.departmentId);
    return pathPids;
  } //获取树形菜单pid的路径
  nodeSelected($event: any) {
    this.option = $event.data.originItem
    this.departmentId = $event.data.originItem.departmentId;
    this.enabled = $event.data.originItem.enable;
    this.UserService.GetUserByDepartmentId(this.departmentId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
      let departmentIdToName = {};
      this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
        departmentIdToName[item.departmentId] = item.name;
      });
      this.tabledata.forEach(item => {
        if (item.departmentId in departmentIdToName) {
          item.departmentId = departmentIdToName[item.departmentId];
        }
      });
    })
    this.pathPids = this.getPathPids(this.option, this.treeData);// 输出路径 PID
  }//树形菜单点击事件
  CreatDepartment(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建部门',
      data: data,
      content: AddDepartmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.PostDepartment.name && results.modalContentInstance.PostDepartment.departmentCode) {
              this.UserService.CreateDepartment(results.modalContentInstance.PostDepartment).subscribe((data: any) => {
                this.showToast('success', '成功', '部门创建成功')
                results.modalInstance.hide();
                this.UserService.GetAllDepartments(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.treeData = data.items
                  this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
                })
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
                results.modalInstance.hide();
              })
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建部门
  EditDepartment(dialogtype?: string) {
    if (this.departmentId) {
      let data = {
        options: this.treeData,
        pathPids: this.pathPids.slice(0, -1),
        display: false,
        option: this.option
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '编辑部门',
        data: data,
        content: EditDepartmentComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (results.modalContentInstance.PutDepartment.name && results.modalContentInstance.PutDepartment.departmentCode) {
                this.UserService.UpdateDepartment(this.departmentId, results.modalContentInstance.PutDepartment).subscribe((data: any) => {
                  this.showToast('success', '成功', '部门编辑成功')
                  results.modalInstance.hide();
                  this.UserService.GetAllDepartments(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                    this.treeData = data.items
                    this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
                    this.pager.total = data.totalCount
                  })
                }, (error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                  results.modalInstance.hide();
                })
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//编辑部门
  DeleteDepartment(dialogtype?: string) {
    if (this.departmentId) {
      const results = this.dialogService.open({
        ...this.config,
        title: '删除部门',
        content: '确认删除该部门？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.UserService.DeleteDepartment(this.departmentId).subscribe((data: any) => {
                this.showToast('success', '成功', '部门删除成功')
                results.modalInstance.hide();
                this.UserService.GetAllDepartments(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.treeData = data.items
                  this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
                  this.pager.total = data.totalCount
                })
              }, (error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              })
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//删除部门
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  searchDepartment($event: any) {
    this.searchDepartmentValue = $event.target.value
    if (this.searchDepartmentValue === '') {
      this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
    }else{
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchDepartmentValue);
      this.displayTreeData = this.filteredTreeNodes
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索部门
  pageIndexChange($event: any) {
    this.pager.pageIndex = $event;
    this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata
      this.pager.total = data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any) {
    this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata
      this.pager.total = data.totalCount;
    })
  }//改变每页显示数量
  disableUsers() {
    this.UserService.DisableUsers(this.checkedIds).subscribe((data: any) => {
      this.showToast('success', '成功', '禁用成功')
      this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata
        this.pager.total = data.totalCount;
        this.checkedIds = []
        this.deleteIDs = []
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//禁用员工
  enableUsers() {
    this.UserService.EnableUsers(this.checkedIds).subscribe((data: any) => {
      this.showToast('success', '成功', '启用成功')
      this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata
        this.pager.total = data.totalCount;
        this.checkedIds = []
        this.deleteIDs = []
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//启用员工
  deleteUsers() {
    this.UserService.DeleteUsers(this.deleteIDs).subscribe((data: any) => {
      this.showToast('success', '成功', '删除成功')
      this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata
        this.pager.total = data.totalCount;
        this.checkedIds = []
        this.deleteIDs = []
      })
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//删除员工
  ResetPassword(rowItem: any, dialogtype?: string) {
    let data = {
      employId: rowItem.employeeCode,
      display: false,
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '更新密码',
      data: data,
      content: ResetPasswordComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.PutPassword.newPassword) {
              this.UserService.AdminResetUserPassword(data.employId, results.modalContentInstance.PutPassword.newPassword).subscribe((data: any) => {
                this.showToast('success', '成功', '密码修改成功')
                results.modalInstance.hide();
                this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                  this.tabledata = data.items;
                  this.pager.total = data.totalCount
                  this.checkedIds = []
                  this.deleteIDs = []
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              })
            } else {
              this.showToast('error', '失败', '密码不能为空')
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//修改密码
  edit(rowitem: any) {
    this.editemployeeId = rowitem.employeeCode
    this.Router.navigate(['/pages/basicdata/edit-employs', this.editemployeeId])
  }//编辑员工
  selctChange() {
    this.Status = this.selectvalue == '全部' ? "all" : this.selectvalue == '启用' ? "enable" : "disable"
    setTimeout(() => {
      this.UserService.GetUserByDepartmentId(this.departmentId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.tabledata = data.items;
        this.displayTableData = this.tabledata;
        this.pager.total = data.totalCount;
        let departmentIdToName = {};
        this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
          departmentIdToName[item.departmentId] = item.name;
        });
        this.tabledata.forEach(item => {
          if (item.departmentId in departmentIdToName) {
            item.departmentId = departmentIdToName[item.departmentId];
          }
        });
      })
    }, 100);
  }//下拉框选择
  search() {
    this.UserService.GetUserByDepartmentId(this.departmentId, this.Status, this.SearchTerm, this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
      let departmentIdToName = {};
      this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
        departmentIdToName[item.departmentId] = item.name;
      });
      this.tabledata.forEach(item => {
        if (item.departmentId in departmentIdToName) {
          item.departmentId = departmentIdToName[item.departmentId];
        }
      });
    })
  }//搜索
  reset() {
    this.Status = null
    this.selectvalue = '全部'
    this.departmentId = null
    this.searchDepartmentValue = ''
    this.SearchTerm = ''
    this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.tabledata = data.items;
      this.displayTableData = this.tabledata;
      this.pager.total = data.totalCount;
      let departmentIdToName = {};
      this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
        departmentIdToName[item.departmentId] = item.name;
      });
      this.tabledata.forEach(item => {
        if (item.departmentId in departmentIdToName) {
          item.departmentId = departmentIdToName[item.departmentId];
        }
      });
    })
  }//重置
  DownloadUserFileModel() {
    this.UserService.DownloadUserFileModel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '员工模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载模板
  // ImportUsersFromExcel(){
  //
  // }//导入员工
  @ViewChild('fileInput1') fileInput1: any;
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  onButtonClick2() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput2.nativeElement.click();
  }
  onFileSelected(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.UserService.importUsersFromExcel(this.file).subscribe({
        next: (data: any) => {
            this.showToast('success', '成功', '导入成功');
            this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
                this.tabledata = data.items;
                this.displayTableData = this.tabledata;
                this.pager.total = data.totalCount;
                let departmentIdToName = {};
                this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
                    departmentIdToName[item.departmentId] = item.name;
                });
                this.tabledata.forEach(item => {
                    if (item.departmentId in departmentIdToName) {
                        item.departmentId = departmentIdToName[item.departmentId];
                    }
                });
            });
        },
        error: (error) => {
          if(error.status==404){
            this.showToast('error', '失败', '服务器连接失败');
          }else{
            this.showToast('error', '失败', error.error);
          }
        },
        complete: () => {
            // 清除文件
            this.file = null;
            event.target.value = ''; // 清空文件输入框
        }
    });
}//导入员工 无论导入成功还是失败都清除文件
  DownloadUserFile() {
    this.UserService.DownloadUserFile().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '员工信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载员工信息
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.displayTableData.forEach(row => {
      if (row.name == '超级管理员') {
        row.$checked = false;
      }
    });
    this.SharedMethodService.getCheckedRows(this.datatable, 'id').subscribe((data: any) => {
      this.deleteIDs = data;
    })
    this.SharedMethodService.getCheckedRows(this.datatable, 'employeeCode').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.deleteIDs, this.tabledata, this.datatable).subscribe((data: any) => {
      this.deleteIDs = data;
    })
  }//清空选中行
  DownloadDepartmentFileModel() {
    this.UserService.DownloadDepartmentFileModel().subscribe((data: any) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '部门模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载部门模板
  ImportDepartmentsFromExcel(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.UserService.ImportDepartmentsFromExcel(this.file).subscribe((data: any) => {
      this.showToast('success', '成功', '导入成功')
      this.UserService.GetAllDepartments(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
        this.treeData = data.items
        this.displayTreeData = [{ name: '全部', departmentId: null }, ...this.treeData];
        if (this.treeData.length > 0) {
          this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
            this.tabledata = data.items;
            this.displayTableData = this.tabledata;
            this.pager.total = data.totalCount;
            let departmentIdToName = {};
            this.treeData.forEach((item: { departmentId: string | number; name: any; }) => {
              departmentIdToName[item.departmentId] = item.name;
            });
            this.tabledata.forEach(item => {
              if (item.departmentId in departmentIdToName) {
                item.departmentId = departmentIdToName[item.departmentId];
              }
            });
          })
        }
      })
    }, (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }//导入部门
  addUser() {
    if (!this.enabled) {
      this.showToast('error', '失败', '部门已禁用')
    } else {
      this.Router.navigate(['/pages/basicdata/add-employs'])
    }
  }//新增员工
  filterCategories(departments: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const department of departments) {
      if (department.name.includes(keyword)) {
        result.push(department);
      }
      if (department.subDepartments.length > 0) {
        const filteredSubCategories = this.filterCategories(department.subDepartments, keyword);
        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }
    return result;
  }
  setOpenTrue = (node: { open: boolean; subDepartments: any[]; }) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subDepartments)) {
      node.subDepartments = node.subDepartments.map(this.setOpenTrue);
    }
    return node;
  }
}
